package com.zhuyuan.auth.controller;

import com.alibaba.fastjson2.JSON;
import com.zhuyuan.auth.from.LoginRequest;
import com.zhuyuan.auth.service.CaptchaService;
import com.zhuyuan.auth.sms.SmsCodeAuthenticationToken;
import com.zhuyuan.core.constant.Oauth2Constants;
import com.zhuyuan.core.enums.ResultCodeEnum;
import com.zhuyuan.core.util.Result;
import com.zhuyuan.system.api.feign.ISysUserApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;


@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class OAuthController {

    private final TokenEndpoint tokenEndpoint;
    private final CaptchaService captchaService;

    /**
     * 验证码获取
     */
    @GetMapping("/code")
    @Operation(
            summary = "验证码获取",
            description = "codeType：普通验证码登录（captcha）手机验证码（sms）"
    )
    public Result<?> getCode(@RequestParam("codeType") String codeType,
                             @RequestParam(value = "mobile", required = false) String mobile) throws HttpRequestMethodNotSupportedException {
        if (codeType.equals(Oauth2Constants.CAPTCHA_GRANT_TYPE)) {
            return captchaService.getCaptchaCode();
        } else if (codeType.equals(Oauth2Constants.SMS_GRANT_TYPE)) {
            return captchaService.getSmsCode(mobile);
        } else {
            throw new HttpRequestMethodNotSupportedException("请检查参数");
        }
    }

    @PostMapping("/login")
    @Operation(
            summary = "用户登录接口",
            description = "grant_type：普通账号验证码登录（captcha）手机号验证码登录（sms）第三方登录（social）"
    )
    public Result<Map<String, Object>> postAccessToken(@RequestBody LoginRequest loginRequest) throws Exception {
        return Result.ok(processLogin(loginRequest));
    }

    private Map<String, Object> processLogin(LoginRequest loginRequest) throws Exception {
        // 反序列化请求体
        Map<String, String> parameters = JSON.parseObject(JSON.toJSONString(loginRequest), Map.class);

        // 创建认证对象
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginRequest.getClient_id(), loginRequest.getClient_secret(), new ArrayList<>());

        // 获取 token
        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(authentication, parameters).getBody();

        // 构建结果
        Map<String, Object> resultData = new LinkedHashMap<>(accessToken.getAdditionalInformation());
        resultData.put("accessToken", accessToken.getValue());
        if (accessToken.getRefreshToken() != null) {
            resultData.put("refreshToken", accessToken.getRefreshToken().getValue());
        }

        return resultData;
    }

    /**
     * 登出
     */
//    @PostMapping("/logOut")
//    @Operation(summary = "登出", description = "登出")
//    @Parameters({
//            @Parameter(name = "Authorization", required = true,  description = "授权码", in = ParameterIn.QUERY)
//    })
//    public R<?> logout(HttpServletRequest request) {
//
//        if (StringUtils.isNotBlank(SecurityUtils.getHeaderToken(request))) {
//            consumerTokenServices.revokeToken(SecurityUtils.getToken(request));
//        }
//
//        return R.ok(null, "登出成功");
//    }

}
